package com.qingjiang.projectschedule.service.impl;


import com.qingjiang.projectschedule.pojo.ProjectInformation;
import com.qingjiang.projectschedule.service.ConfigService;
import com.qingjiang.projectschedule.service.ProjectInformationService;
import com.qingjiang.projectschedule.service.ProjectNodeService;
import com.qingjiang.projectschedule.service.UserInfoService;
import com.qingjiang.projectschedule.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ScheduledSendMessage {
    @Autowired
    private ProjectInformationService projectInformationService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private ProjectNodeService projectNodeService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

    //cron = "0 40 16 * * ?"
    @Scheduled(cron = "0 30 8 * * ?")
    public void sendTaskForEveryday() {
        Map<String, List<ProjectInformation>> delayProjectList = projectInformationService.getDelayProjectList();
        List<ProjectInformation> postponedProjects = delayProjectList.get("postponedProjects");
        List<ProjectInformation> checkProjects = delayProjectList.get("checkProjects");
        if (postponedProjects != null && !postponedProjects.isEmpty()) {
            generateMessageAndSend(postponedProjects, "超期");
        }
        if (checkProjects != null && !checkProjects.isEmpty()) {
            generateMessageAndSend(checkProjects, "考核");
        }
    }

    public void generateMessageAndSend(List<ProjectInformation> projects, String type) {
        for (ProjectInformation postponedProject : projects) {
            String projectName = postponedProject.getProjectName();
            String nodeName = projectNodeService.getNodeNameById(postponedProject.getCurrentNodeid());
            List<Map<String, Object>> userForSendMessage = userInfoService.getUserForSendMessage(postponedProject.getDeptId());
            if (userForSendMessage != null && !userForSendMessage.isEmpty()) {
                StringBuilder users = new StringBuilder();
                for (int i = 0; i < userForSendMessage.size(); i++) {
                    users.append(userForSendMessage.get(i).get("username").toString());
                    if (i < userForSendMessage.size() - 1) {
                        users.append("，");
                    }
                }
                System.out.println("users:" + users.toString());
                String postDate = sdf.format(DateUtil.DateAdd(new Date(), configService.getMessageDays()));
                String message = "《" + projectName + "》项目「" + nodeName + "」节点将于" + postDate + type + "，请及时办理。";
                sendMessage(verifyCode(users.toString(), message));
            }
        }
    }

    public String verifyCode(String toUserName, String MsgContent) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://172.16.101.67/qdcsmscenter/SmsService/webservice.asmx";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/soap+xml; charset=utf-8");
        String param = "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n" +
                "  <soap12:Body>\n" +
                "    <CreateVerifyCode xmlns=\"http://tempuri.org/\">\n" +
                "      <isTrust>1</isTrust>\n" +
                "      <createUserName>项目进度管理系统</createUserName>\n" +
                "      <fromSystem>F66FF144-434B-4666-A0FC-5797334597F2</fromSystem>\n" +
                "      <fromModule></fromModule>\n" +
                "      <ToUserName>" + toUserName + "</ToUserName>\n" +
                "      <MsgContent>" + MsgContent + "</MsgContent>\n" +
                "    </CreateVerifyCode>\n" +
                "  </soap12:Body>\n" +
                "</soap12:Envelope>";
        HttpEntity<String> entity = new HttpEntity<>(param, headers);
        String result = restTemplate.postForObject(url, entity, String.class);
        int start = result.indexOf("<CreateVerifyCodeResult>");
        int end = result.indexOf("</CreateVerifyCodeResult>");
        result = result.substring(start + "<CreateVerifyCodeResult>".length(), end);
        return result;
    }

    public void sendMessage(String verifyCode) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://172.16.101.67/qdcsmscenter/SmsService/webservice.asmx";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/soap+xml; charset=utf-8");
        String param2 = "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n" +
                "  <soap12:Body>\n" +
                "    <WebServiceSendMsg xmlns=\"http://tempuri.org/\">\n" +
                "      <verifyCode>" + verifyCode + "</verifyCode>\n" +
                "    </WebServiceSendMsg>\n" +
                "  </soap12:Body>\n" +
                "</soap12:Envelope>";
        HttpEntity<String> entity2 = new HttpEntity<>(param2, headers);
        restTemplate.postForObject(url, entity2, String.class);
    }
}
